package com.aisi.manager.interceptor;

import cn.hutool.core.util.StrUtil;
import com.aisi.commonUtil.AuthContextUtil;
import com.aisi.model.entity.system.SysUser;
import com.aisi.model.vo.common.Result;
import com.aisi.model.vo.common.ResultCodeEnum;
import com.alibaba.fastjson2.JSON;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @Author: shenjianZ
 * @Date: 2024/2/17 9:26
 * @Description:
 */

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 对请求进行预处理，执行特定的逻辑操作
     *
     * @param request HTTP请求
     * @param response HTTP响应
     * @param handler Handler对象
     * @return 返回处理结果，true表示允许继续处理，false表示终止处理
     * @throws Exception 抛出异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
//        System.out.println(request.getRequestURI());
//        if(request.getRequestURI().contains("doc.html"))
//            return true;
        if ("OPTIONS".equals(method))
            return true; // 允许跨域请求
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)) {
            responseNoLoginInfo(response);//token为空，返回未登录信息
            return false;
        }
        String userInfo = redisTemplate.opsForValue().get("user:login" + token);
        if (StrUtil.isEmpty(userInfo)) {
            responseNoLoginInfo(response);//token失效，返回未登录信息
            return false;
        }
        // 将用户信息转成SysUser对象，并设置到线程上下文中
        AuthContextUtil.setAuthContext(JSON.parseObject(userInfo, SysUser.class));
        redisTemplate.expire("user:login" + token, 30, TimeUnit.MINUTES); // 延长token有效期,防止token过期
        // 放行
        return true;

    }

    /**
     * 返回未登录信息响应
     *
     * @param response HttpServletResponse对象
     */
    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.removeAuthContext();    // 清除用户信息上下文
    }
}
